Handle Check Box in Selenium
Code of Check Box
package asc; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import io.github.bonigarcia.wdm.WebDriverManager; public class CheckBox { public static void main(String[] args) throws InterruptedException { WebDriverManager.chromedriver().setup(); WebDriver driver = new ChromeDriver(); driver.get("https://www.flipkart.com/search?q=shoes&as=on&as-show=on&otracker=AS_Query_TrendingAutoSuggest_2_0_na_na_na& otracker1=AS_Query_TrendingAutoSuggest_2_0_na_na_na&as-pos=2&as-type=TRENDING&suggestionId=shoes&requestId=b7ce4969-8a9e-45e7-a7f2-0fcbd9eafdfe"); driver.manage().window().maximize(); //driver.findElement(By.id("//*[@id=\"container\"]/div/div[3]/div[1]/div[1]/div/div/div/section[2]/div[1]")).click(); //Thread.sleep(2000); driver.findElement(By.xpath("//*[@id=\"container\"]/div/div[3]/div[1]/div[1]/div/div/div/section[3]/label/div[2]/div")).click(); Thread.sleep(2000); driver.findElement(By.xpath("//*[@id=\"container\"]/div/div[3]/div[1]/div[1]/div/div/div/section[3]/label/div[2]/div")).click(); } }
Output

After Running the code



In Selenium WebDriver, interacting with checkboxes involves locating the checkbox element on the webpage and performing actions like clicking to select or deselect it. Here's a breakdown of your provided code and some general information on handling checkboxes in Selenium:
Breakdown of Your Code
1. Setup WebDriver:
WebDriverManager.chromedriver().setup(); WebDriver driver = new ChromeDriver(); driver.get("https://www.flipkart.com/search?q=shoes&as=on&as-show=on&otracker=AS_Query_TrendingAutoSuggest_2_0_na_na_na&otracker1=AS_Query_TrendingAutoSuggest_2_0_na_na_na&as-pos=2&as-type=TRENDING&suggestionId=shoes&requestId=b7ce4969-8a9e-45e7-a7f2-0fcbd9eafdfe"); driver.manage().window().maximize();
2. Interacting with Checkboxes:
driver.findElement(By.xpath("//*[@id=\"container\"]/div/div[3]/div[1]/div[1]/div/div/div/section[3]/label/div[2]/div")).click(); Thread.sleep(2000); driver.findElement(By.xpath("//*[@id=\"container\"]/div/div[3]/div[1]/div[1]/div/div/div/section[3]/label/div[2]/div")).click();
Handling Checkboxes in Selenium
Locating Checkboxes:
- Checkboxes are typically located using attributes like id, name, class, or custom attributes. If these attributes are not present or suitable, XPath or CSS selectors can be used, as in your example.
Clicking Checkboxes:
- The click() method toggles the checkbox state. If the checkbox is unchecked, it will become checked, and vice versa. In your code, the checkbox is clicked twice, which toggles it on and then off again.
Checking Checkbox Status:
- To verify whether a checkbox is selected, use the isSelected() method:
boolean isChecked = driver.findElement(By.xpath("your_xpath_here")).isSelected();
- This method returns true if the checkbox is selected and false if it's not.